<template>
  <div class="flex h-screen w-full bg-gray-50 px-24 py-4">
    <!-- 左侧控制面板 -->
    <div class="w-[30rem] min-w-[30rem] max-w-[34rem] border-r border-gray-200 bg-white flex flex-col rounded-lg shadow-sm">
      <!-- 标题和按钮区域 -->
      <div class="p-4 border-b border-gray-200">
        <div class="flex items-center justify-between mb-3">
          <h1 class="text-lg font-semibold text-gray-800 truncate">
            {{ scriptName ? `脚本编辑 - ${scriptName}` : '脚本编辑 - 登录流程测试' }}
          </h1>
          <el-tag v-if="scriptName" type="info" size="small" style="margin-left: 10px">
            关联脚本: {{ scriptName }}
          </el-tag>
        </div>

         <!-- 高级按钮组 -->
         <div class="grid grid-cols-4 gap-2 mb-4">
           <el-button
             type="primary"
             class="premium-button primary-button h-12 text-sm font-medium"
             @click="saveScript"
           >
             <el-icon class="mr-2 text-base"><i-ep-upload /></el-icon>保存
           </el-button>

           <el-dropdown placement="bottom-start" @command="handleFileCommand">
             <el-button class="premium-button white-button h-12 text-sm font-medium">
               <el-icon class="mr-2 text-base"><i-ep-folder /></el-icon>文件
               <el-icon class="ml-2 text-sm"><i-ep-arrow-down /></el-icon>
             </el-button>
             <template #dropdown>
               <el-dropdown-menu>
                 <el-dropdown-item command="import">
                   <el-icon class="mr-2 text-blue-600"><i-ep-upload /></el-icon>导入脚本
                 </el-dropdown-item>
                 <el-dropdown-item command="export">
                   <el-icon class="mr-2 text-green-600"><i-ep-download /></el-icon>导出脚本
                 </el-dropdown-item>
               </el-dropdown-menu>
             </template>
           </el-dropdown>

           <el-button
             class="premium-button white-button h-12 text-sm font-medium"
             @click="showNewStepModal"
           >
             <el-icon class="mr-2 text-base"><i-ep-plus /></el-icon>新建
           </el-button>

           <el-button
             class="premium-button white-button h-12 text-sm font-medium"
             :loading="isExecuting"
             :disabled="!hasSteps"
             @click="executeAll"
           >
             <el-icon class="mr-2 text-base"><i-ep-caret-right /></el-icon>执行
           </el-button>
         </div>

        <!-- 录制控制 -->
        <div class="mb-2">
          <RecordingControls />
        </div>
      </div>

      <!-- 步骤列表区域 -->
      <div class="flex-1 overflow-auto">
        <div class="p-4">
          <div v-if="hasSteps || isRecording" class="mt-1">
            <div class="flex items-center justify-between mb-3">
              <h3 class="text-lg font-semibold text-gray-800">录制步骤</h3>
              <span class="text-xs text-white bg-blue-500 px-2 py-1 rounded-full font-medium">{{ stepCount }} 个步骤</span>
            </div>
            <div class="bg-white rounded-lg p-3 border border-gray-200 shadow-sm">
              <StepList
                :readonly="true"
                :show-code="false"
                :show-recording-steps="isRecording || recordingStore.hasRecordedSteps"
                @step-selected="selectStep"
                @step-edited="editStep"
              />
            </div>
          </div>

          <div v-else id="emptyStepsMessage" class="text-center py-8">
            <div class="p-6">
              <div class="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
                <el-icon class="text-2xl text-gray-400"><i-ep-plus /></el-icon>
              </div>
              <h3 class="text-lg font-semibold mb-2 text-gray-800">还没有测试步骤</h3>
              <p class="text-sm text-gray-600 leading-relaxed">点击"导入脚本"开始，或使用"新步骤"手动添加</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="flex-1 flex flex-col min-w-0 ml-12">
      <!-- 顶部按钮式标签栏 -->
      <div class="flex border-b border-gray-200 bg-white flex-shrink-0 rounded-lg shadow-sm p-1">
        <button
          id="paramLocatorBtn"
          class="advanced-tab-button px-6 py-4 text-sm font-medium flex-shrink-0 transition-all duration-300"
          :class="activeTab === 'params' ? 'tab-active' : 'tab-inactive'"
          @click="activeTab = 'params'"
        >
          <el-icon class="mr-2 text-base">
            <i-ep-edit />
          </el-icon>
          参数与定位
        </button>
        <button
          id="logBtn"
          class="advanced-tab-button px-6 py-4 text-sm font-medium flex-shrink-0 transition-all duration-300"
          :class="activeTab === 'logs' ? 'tab-active' : 'tab-inactive'"
          @click="activeTab = 'logs'"
        >
          <el-icon class="mr-2 text-base">
            <i-ep-document />
          </el-icon>
          日志
        </button>
        <button
          id="consoleBtn"
          class="advanced-tab-button px-6 py-4 text-sm font-medium flex-shrink-0 transition-all duration-300"
          :class="activeTab === 'console' ? 'tab-active' : 'tab-inactive'"
          @click="activeTab = 'console'"
        >
          <el-icon class="mr-2 text-base">
            <i-ep-monitor />
          </el-icon>
          控制台
        </button>
        <button
          id="previewBtn"
          class="advanced-tab-button px-6 py-4 text-sm font-medium flex-shrink-0 transition-all duration-300"
          :class="activeTab === 'preview' ? 'tab-active' : 'tab-inactive'"
          @click="activeTab = 'preview'"
        >
          <el-icon class="mr-2 text-base">
            <i-ep-view />
          </el-icon>
          预览
        </button>
      </div>

      <!-- 内容区 -->
      <div class="tab-content flex-1 bg-white overflow-hidden rounded-b-lg shadow-sm">
        <!-- 参数与定位 -->
        <div v-if="activeTab === 'params'" class="h-full overflow-auto">
          <ParameterEditor />
        </div>

        <!-- 日志 -->
        <div v-else-if="activeTab === 'logs'" class="h-full overflow-auto">
          <ExecutionLogger />
        </div>

        <!-- 控制台 -->
        <div v-else-if="activeTab === 'console'" class="h-full overflow-auto">
          <ConsolePanel />
        </div>

               <!-- 预览 -->
               <div v-else-if="activeTab === 'preview'" class="h-full overflow-auto">
                 <PreviewPanel />
               </div>
      </div>
    </div>

    <!-- 弹窗组件 -->
    <NewStepModal v-model:visible="showNewStepModalFlag" @confirm="handleNewStep" />
    <ImportScriptModal v-model:visible="showImportModalFlag" @confirm="handleScriptImport" />
    <ExportScriptModal v-model:visible="showExportModalFlag" @confirm="handleScriptExport" />
    <EditStepModal v-model:visible="showEditStepModalFlag" :step="selectedStep" @confirm="handleEditStepConfirm" @delete="handleDeleteStep" @move="handleMoveStep" />
    <MoveStepModal v-model:visible="showMoveStepModalFlag" :step="stepToMove" @confirm="handleStepMove" />
    
    <!-- 脚本保存确认弹窗 -->
    <el-dialog
      v-model="showSaveConfirmDialog"
      title="确认保存脚本"
      width="90%"
      :close-on-click-modal="false"
      style="max-width: 1400px;"
    >
      <div class="flex gap-4" style="max-height: 60vh; overflow-y: auto;">
        <!-- 左侧：原始数据（不可编辑） -->
        <div class="flex-1 border rounded p-4 bg-gray-50">
          <h3 class="text-lg font-semibold mb-4 text-gray-700">数据库中的原始脚本</h3>
          <el-form label-width="100px" label-position="top">
            <el-form-item label="脚本名称">
              <el-input v-model="originalScript.name" :disabled="true" />
            </el-form-item>
            <el-form-item label="脚本描述">
              <el-input v-model="originalScript.description" type="textarea" :rows="4" :disabled="true" />
            </el-form-item>
            <el-form-item label="脚本代码">
              <el-input 
                v-model="originalScript.code" 
                type="textarea" 
                :rows="15" 
                :disabled="true"
                style="font-family: monospace; font-size: 12px;"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 右侧：修改后的数据（可编辑） -->
        <div class="flex-1 border rounded p-4 bg-white">
          <h3 class="text-lg font-semibold mb-4 text-blue-700">修改后的脚本</h3>
          <el-form label-width="100px" label-position="top">
            <el-form-item label="脚本名称">
              <el-input v-model="updatedScript.name" placeholder="请输入脚本名称" />
            </el-form-item>
            <el-form-item label="脚本描述">
              <el-input v-model="updatedScript.description" type="textarea" :rows="4" placeholder="请输入脚本描述" />
            </el-form-item>
            <el-form-item label="脚本代码">
              <el-input 
                v-model="updatedScript.code" 
                type="textarea" 
                :rows="15"
                placeholder="脚本代码"
                style="font-family: monospace; font-size: 12px;"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showSaveConfirmDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmSaveScript" :loading="savingScript">确认保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, computed } from 'vue'
import { useScriptStore } from '../stores/script'
import { useExecutionStore } from '../stores/execution'
import { useRecordingStore } from '../stores/recording'
import { handleError, ErrorTypes, ErrorLevels } from '../utils/errorHandler'
import { ElMessage, ElMessageBox } from 'element-plus'

// 组件导入
import ExecutionLogger from '../components/ExecutionLogger.vue'
import ConsolePanel from '../components/ConsolePanel.vue'
import NewStepModal from '../components/NewStepModal.vue'
import ImportScriptModal from '../components/ImportScriptModal.vue'
import ExportScriptModal from '../components/ExportScriptModal.vue'
import EditStepModal from '../components/EditStepModal.vue'
import MoveStepModal from '../components/MoveStepModal.vue'
import RecordingControls from '../components/RecordingControls.vue'
import StepList from '../components/StepList.vue'
import ParameterEditor from '../components/ParameterEditor.vue'
import PreviewPanel from '../components/PreviewPanel.vue'

// Element Plus 图标
import {
  Upload as iEpUpload,
  Plus as iEpPlus,
  VideoPlay as iEpVideoPlay,
  VideoPause as iEpVideoPause,
  VideoCamera as iEpVideoCamera,
  Search as iEpSearch,
  ArrowLeft as iEpArrowLeft,
  ArrowRight as iEpArrowRight,
  ArrowDown as iEpArrowDown,
  Refresh as iEpRefresh,
  Monitor as iEpMonitor,
  Edit as iEpEdit,
  Delete as iEpDelete,
  Check as iEpCheck,
  Close as iEpClose,
  Loading as iEpLoading,
  CircleCloseFilled as iEpCircleCloseFilled,
  Link as iEpLink,
  Promotion as iEpPromotion,
  Mouse as iEpMouse,
  View as iEpView,
  Clock as iEpClock,
  Camera as iEpCamera,
  Document as iEpDocument,
  Aim as iEpAim,
  Folder as iEpFolder,
  FolderOpened as iEpFolderOpened,
  Download as iEpDownload,
  CaretRight as iEpCaretRight,
  List as iEpList
} from '@element-plus/icons-vue'

import { useRoute } from 'vue-router'
import { managementApiService } from '../services/managementApiService.js'
import { recordingManager } from '../services/recordingManager.js'

const route = useRoute()
const scriptStore = useScriptStore()
const executionStore = useExecutionStore()
const recordingStore = useRecordingStore()

// 从路由参数获取脚本名称
const scriptName = computed(() => route.query.scriptName || null)

// 响应式数据
const activeTab = ref('params')
const selectedStep = ref(null)
const previewUrl = ref('https://example.com/login')
const showNewStepModalFlag = ref(false)
const showImportModalFlag = ref(false)
const showExportModalFlag = ref(false)
const showEditStepModalFlag = ref(false)
const showMoveStepModalFlag = ref(false)
const stepToMove = ref(null)
const showCleanupButton = ref(false)

// 脚本保存确认弹窗相关
const showSaveConfirmDialog = ref(false)
const savingScript = ref(false)
const currentScriptId = ref(null)
const originalScript = ref({
  name: '',
  description: '',
  code: ''
})
const updatedScript = ref({
  name: '',
  description: '',
  code: ''
})

// 参数编辑数据
const parameterData = ref({
  locator: '#username',
  inputValue: 'admin@example.com',
  waitTime: 1000,
  timeout: 5000
})

// 计算属性
const hasSteps = computed(() => scriptStore.hasSteps || recordingStore.hasRecordedSteps)
const stepCount = computed(() => {
  // 如果有录制步骤，优先显示录制步骤数量，否则显示脚本步骤数量
  if (recordingStore.hasRecordedSteps) {
    return recordingStore.recordingSteps.length
  }
  return scriptStore.stepCount
})
const isExecuting = computed(() => executionStore.isExecuting)
const isPaused = computed(() => executionStore.isPaused)
const isRecording = computed(() => recordingStore.isRecording)
const executionStatus = computed(() => executionStore.executionStatus)

// 方法
const saveScript = async () => {
  try {
    // 如果有脚本名称参数，说明是从管理页面跳转过来的，需要更新后端脚本
    if (scriptName.value) {
      // 获取当前录制的脚本代码
      let newScriptCode = ''
      
      // 优先使用录制的脚本内容（如果存在）
      if (recordingManager.lastScriptContent) {
        newScriptCode = recordingManager.lastScriptContent
      } else if (scriptStore.hasSteps) {
        // 否则从scriptStore导出脚本代码
        const exported = scriptStore.exportScript({ format: 'playwright' })
        newScriptCode = exported.content || ''
      } else {
        ElMessage.warning('当前没有可保存的脚本内容')
        return
      }
      
      // 从后端查询脚本详情
      try {
        ElMessage.info('正在加载脚本信息...')
        
        // 先通过名称查找脚本ID
        const scriptList = await managementApiService.getScripts({ page: 0, size: 100 })
        const scriptData = scriptList?.data?.content || scriptList?.data || []
        
        // 查找匹配的脚本
        const matchedScript = scriptData.find(script => {
          const name = script.script_name || script.name
          return name === scriptName.value
        })
        
        if (!matchedScript) {
          ElMessage.error(`未找到脚本: ${scriptName.value}`)
          return
        }
        
        // 保存脚本ID
        const scriptId = matchedScript.script_id || matchedScript.id
        currentScriptId.value = scriptId
        
        // 使用脚本ID获取完整详情（包含完整的代码和描述）
        const scriptDetail = await managementApiService.getScript(scriptId)
        const scriptInfo = scriptDetail?.data || scriptDetail
        
        // 设置原始数据（不可编辑）
        // 确保字段映射正确：script_description 对应描述，script_code 对应代码
        originalScript.value = {
          name: scriptInfo.script_name || scriptInfo.name || matchedScript.script_name || matchedScript.name || '',
          description: scriptInfo.script_description || scriptInfo.description || matchedScript.script_description || matchedScript.description || '',
          code: scriptInfo.script_code || scriptInfo.code || matchedScript.script_code || matchedScript.code || ''
        }
        
        // 调试输出，检查字段映射
        console.log('原始脚本数据:', {
          script_name: originalScript.value.name,
          script_description: originalScript.value.description?.substring(0, 50),
          script_code_length: originalScript.value.code?.length || 0
        })
        
        // 设置修改后的数据（可编辑），脚本名称和描述默认使用数据库值，代码使用新录制的
        updatedScript.value = {
          name: originalScript.value.name,
          description: originalScript.value.description,
          code: newScriptCode
        }
        
        // 显示确认弹窗
        showSaveConfirmDialog.value = true
        
      } catch (error) {
        console.error('查询脚本详情失败:', error)
        ElMessage.error('查询脚本详情失败: ' + error.message)
      }
    } else {
      // 没有脚本名称参数，使用原有的保存逻辑
      await scriptStore.saveScript()
      ElMessage.success('脚本已保存')
    }
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 确认保存脚本
const confirmSaveScript = async () => {
  try {
    savingScript.value = true
    
    // 验证必填字段
    if (!updatedScript.value.name || !updatedScript.value.name.trim()) {
      ElMessage.warning('脚本名称不能为空')
      return
    }
    
    if (!currentScriptId.value) {
      ElMessage.error('脚本ID缺失')
      return
    }
    
    // 调用更新接口，传递完整的脚本信息
    await managementApiService.updateScript(currentScriptId.value, {
      script_id: currentScriptId.value,
      script_name: updatedScript.value.name.trim(),
      script_description: updatedScript.value.description || '',
      script_code: updatedScript.value.code || ''
    })
    
    ElMessage.success('脚本保存成功')
    showSaveConfirmDialog.value = false
    
  } catch (error) {
    console.error('保存脚本失败:', error)
    ElMessage.error('保存失败: ' + error.message)
  } finally {
    savingScript.value = false
  }
}

const showNewStepModal = () => {
  showNewStepModalFlag.value = true
}

// 文件操作相关方法
const handleFileCommand = (command) => {
  switch (command) {
    case 'import':
      showImportModalFlag.value = true
      break
    case 'export':
      showExportModalFlag.value = true
      break
  }
}


// 执行控制相关方法
const executeNextStep = async () => {
  try {
    await executionStore.executeNextStep(scriptStore.steps)
    ElMessage.success('步骤执行完成')
  } catch (error) {
    ElMessage.error('执行失败: ' + error.message)
  }
}

const executeAll = async () => {
  try {
    const steps = scriptStore.steps
    if (steps.length === 0) {
      ElMessage.warning('没有可执行的步骤')
      return
    }

    await ElMessageBox.confirm(
      `确定要执行全部 ${steps.length} 个步骤吗？`,
      '确认执行',
      {
        confirmButtonText: '执行',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await executionStore.executeAll(steps)
    ElMessage.success('开始执行测试脚本...')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('执行失败: ' + error.message)
    }
  }
}

const pauseResume = async () => {
  try {
    if (isPaused.value) {
      await executionStore.resume()
      ElMessage.success('执行已恢复')
    } else {
      await executionStore.pause()
      ElMessage.success('执行已暂停')
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  }
}

const resetExecution = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置执行状态吗？这将清除当前的执行进度。',
      '确认重置',
      {
        confirmButtonText: '重置',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await executionStore.reset()
    ElMessage.success('执行状态已重置')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重置失败: ' + error.message)
    }
  }
}

// 录制功能已移至RecordingControls组件

// 自动导入生成的脚本
const autoImportGeneratedScript = async (scriptContent) => {
  try {
    console.log('自动导入生成的脚本...')
    
    // 使用脚本管理器导入脚本
    const { scriptManager } = await import('../services/scriptManager.js')
    const result = await scriptManager.autoImportGeneratedScript(scriptContent)
    
    if (result.success) {
      console.log('脚本自动导入成功')
      // 触发Vue组件的步骤更新
      if (scriptStore.importScript) {
        scriptStore.importScript(scriptContent, 'playwright')
      }
    }
  } catch (error) {
    console.error('自动导入脚本失败:', error)
  }
}

const cleanupRecording = async () => {
  try {
    await recordingStore.cleanup()
    ElMessage.success('录制状态已清理')
    showCleanupButton.value = false
  } catch (error) {
    ElMessage.error('清理失败: ' + error.message)
  }
}

const handleNewStep = async (stepData) => {
  try {
    await scriptStore.addStep(stepData)
    ElMessage.success('步骤添加成功')
    showNewStepModalFlag.value = false
  } catch (error) {
    ElMessage.error('添加失败: ' + error.message)
  }
}

const handleScriptImport = async (scriptData) => {
  try {
    // 使用script store导入脚本
    await scriptStore.importScript(scriptData.content, scriptData.format)
    
    // 如果有解析的步骤，直接添加到store中
    if (scriptData.steps && scriptData.steps.length > 0) {
      // 清空现有步骤
      scriptStore.clearSteps()
      
      // 添加新步骤
      scriptData.steps.forEach((step, index) => {
        const scriptStep = {
          stepNumber: step.stepNumber || (index + 1),
          type: step.type,
          action: step.action,
          description: step.description || step.name,
          selector: step.selector,
          value: step.value,
          url: step.url,
          timestamp: step.timestamp || new Date().toISOString(),
          status: 'pending'
        }
        scriptStore.addStep(scriptStep)
      })
    }
    
    ElMessage.success('脚本导入成功')
    showImportModalFlag.value = false
  } catch (error) {
    ElMessage.error('导入失败: ' + error.message)
  }
}

const handleScriptExport = async (exportOptions) => {
  try {
    const exportedScript = await scriptStore.exportScript(exportOptions)
    ElMessage.success('脚本导出成功')
    showExportModalFlag.value = false
    
    // 创建下载链接
    const blob = new Blob([exportedScript.content], { type: 'text/plain' })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = exportedScript.filename
    a.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    ElMessage.error('导出失败: ' + error.message)
  }
}

// 步骤编辑相关方法
const handleEditStepConfirm = async (stepData) => {
  try {
    if (selectedStep.value) {
      await scriptStore.updateStep(selectedStep.value.stepNumber, stepData)
      ElMessage.success('步骤更新成功')
      showEditStepModalFlag.value = false
      selectedStep.value = null
    }
  } catch (error) {
    ElMessage.error('更新失败: ' + error.message)
  }
}

const handleDeleteStep = async (step) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除步骤 "${step.description || step.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await scriptStore.removeStep(step.stepNumber)
    ElMessage.success('步骤删除成功')
    showEditStepModalFlag.value = false
    selectedStep.value = null
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

const handleMoveStep = (step) => {
  stepToMove.value = step
  showMoveStepModalFlag.value = true
  showEditStepModalFlag.value = false
}

const handleStepMove = async (moveData) => {
  try {
    const { fromIndex, toIndex } = moveData
    await scriptStore.moveStep(fromIndex, toIndex)
    ElMessage.success('步骤移动成功')
    showMoveStepModalFlag.value = false
    stepToMove.value = null
  } catch (error) {
    ElMessage.error('移动失败: ' + error.message)
  }
}

// 编辑步骤方法（用于步骤列表点击编辑）
const editStep = (step) => {
  selectedStep.value = step
  showEditStepModalFlag.value = true
}

const selectStep = (step) => {
  selectedStep.value = step
  // 可以在这里添加选择步骤后的逻辑，比如高亮显示等
}

// 辅助方法 - 获取步骤类型名称
const getStepTypeName = (type) => {
  const typeNames = {
    navigation: '导航',
    input: '输入文本',
    click: '点击',
    select: '选择',
    wait: '等待',
    assertion: '断言',
    screenshot: '截图'
  }
  return typeNames[type] || type
}

// 辅助方法 - 获取步骤状态名称
const getStepStatusName = (status) => {
  const statusNames = {
    pending: '待执行',
    running: '执行中',
    success: '已成功',
    failed: '已失败',
    skipped: '已跳过'
  }
  return statusNames[status] || status
}

// 辅助方法 - 获取步骤状态类型（用于el-tag的type属性）
const getStepStatusType = (status) => {
  const statusTypes = {
    pending: '',
    running: 'warning',
    success: 'success',
    failed: 'danger',
    skipped: 'info'
  }
  return statusTypes[status] || ''
}

</script>

<style scoped>
body {
  min-height: 100vh;
}

.rounded-button {
  border-radius: 8px !important;
}

/* 标签过渡动画 */
.tab-content {
  transition: opacity 0.3s ease-in-out;
}

/* 按钮组样式 */
.whitespace-nowrap {
  white-space: nowrap;
}

/* 高级按钮样式 */
.premium-button {
  @apply relative overflow-hidden transition-all duration-300 ease-out;
  @apply border-2 rounded-xl font-semibold;
  @apply transform hover:scale-105 active:scale-95;
  @apply shadow-lg hover:shadow-xl;
  @apply backdrop-blur-sm;
}

/* 主按钮样式 */
.primary-button {
  @apply bg-gradient-to-r from-blue-600 to-blue-700;
  @apply border-blue-500 text-white;
  @apply hover:from-blue-700 hover:to-blue-800;
  @apply hover:border-blue-600;
  @apply shadow-blue-500/25 hover:shadow-blue-500/40;
}

.primary-button:hover {
  @apply shadow-2xl;
  box-shadow: 0 20px 25px -5px rgba(59, 130, 246, 0.4), 0 10px 10px -5px rgba(59, 130, 246, 0.2);
}

.primary-button:active {
  @apply scale-95;
}

/* 次要按钮样式 - 浅蓝色主题，与主按钮保持一致 */
.secondary-button {
  @apply bg-gradient-to-r from-blue-50 to-blue-100;
  @apply border-blue-200 text-blue-700;
  @apply hover:from-blue-100 hover:to-blue-200;
  @apply hover:border-blue-300;
  @apply shadow-blue-500/10 hover:shadow-blue-500/20;
}

.secondary-button:hover {
  @apply shadow-lg;
  box-shadow: 0 10px 15px -3px rgba(59, 130, 246, 0.2), 0 4px 6px -2px rgba(59, 130, 246, 0.1);
}

/* 强调按钮样式 - 保持蓝色主题统一 */
.accent-button {
  @apply bg-gradient-to-r from-blue-500 to-blue-600;
  @apply border-blue-500 text-white;
  @apply hover:from-blue-600 hover:to-blue-700;
  @apply hover:border-blue-600;
  @apply shadow-blue-500/25 hover:shadow-blue-500/40;
}

.accent-button:hover {
  @apply shadow-2xl;
  box-shadow: 0 20px 25px -5px rgba(59, 130, 246, 0.4), 0 10px 10px -5px rgba(59, 130, 246, 0.2);
}

/* 成功按钮样式 */
.success-button {
  @apply bg-gradient-to-r from-green-600 to-green-700;
  @apply border-green-500 text-white;
  @apply hover:from-green-700 hover:to-green-800;
  @apply hover:border-green-600;
  @apply shadow-green-500/25 hover:shadow-green-500/40;
}

.success-button:hover {
  @apply shadow-2xl;
  box-shadow: 0 20px 25px -5px rgba(34, 197, 94, 0.4), 0 10px 10px -5px rgba(34, 197, 94, 0.2);
}

/* 白色按钮样式 - 高级设计 */
.white-button {
  @apply bg-white;
  @apply border-2 border-gray-200 text-gray-700;
  @apply hover:bg-gray-50 hover:border-gray-300;
  @apply shadow-sm hover:shadow-md;
  @apply transition-all duration-200;
}

.white-button:hover {
  @apply transform scale-105;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.white-button:active {
  @apply scale-95;
}

/* 高级标签按钮样式 */
.advanced-tab-button {
  @apply relative overflow-hidden;
  @apply rounded-lg mx-1;
  @apply transform transition-all duration-300 ease-out;
  @apply hover:scale-105 active:scale-95;
  @apply backdrop-blur-sm;
}

/* 激活状态标签按钮 */
.tab-active {
  @apply bg-gradient-to-r from-blue-500 to-blue-600;
  @apply text-white shadow-lg;
  @apply border-2 border-blue-500;
  @apply shadow-blue-500/25;
}

.tab-active:hover {
  @apply from-blue-600 to-blue-700;
  @apply shadow-blue-500/40;
  @apply shadow-xl;
  box-shadow: 0 20px 25px -5px rgba(59, 130, 246, 0.4), 0 10px 10px -5px rgba(59, 130, 246, 0.2);
}

/* 非激活状态标签按钮 */
.tab-inactive {
  @apply bg-white;
  @apply text-gray-600 border-2 border-transparent;
  @apply hover:bg-gray-50 hover:text-gray-800;
  @apply hover:border-gray-200;
  @apply shadow-sm hover:shadow-md;
}

.tab-inactive:hover {
  @apply transform scale-105;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

/* 标签按钮悬浮效果 */
.advanced-tab-button::before {
  content: '';
  @apply absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent;
  @apply transform -skew-x-12 -translate-x-full;
  @apply transition-transform duration-700;
}

.advanced-tab-button:hover::before {
  @apply translate-x-full;
}

/* 标签按钮激活动画 */
.tab-active::after {
  content: '';
  @apply absolute bottom-0 left-0 right-0 h-1;
  @apply bg-gradient-to-r from-white/50 to-white/30;
  @apply animate-pulse;
}

/* 标签按钮图标动画 */
.advanced-tab-button .el-icon {
  @apply transition-transform duration-300;
}

.advanced-tab-button:hover .el-icon {
  @apply scale-110;
}

.tab-active .el-icon {
  @apply animate-pulse;
}

/* 按钮状态样式 */
.premium-button:disabled {
  @apply opacity-50 cursor-not-allowed;
  @apply transform-none hover:scale-100;
  @apply shadow-none hover:shadow-none;
}

.premium-button.loading {
  @apply relative;
}

.premium-button.loading::before {
  content: '';
  @apply absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent;
  @apply animate-pulse;
}

/* 按钮选中状态 */
.premium-button.selected {
  @apply ring-4 ring-blue-500/30;
  @apply scale-105;
}

/* 按钮等待状态 */
.premium-button.waiting {
  @apply animate-pulse;
  @apply bg-gradient-to-r from-yellow-400 to-orange-500;
  @apply border-yellow-400;
}

/* 按钮悬浮效果 */
.premium-button::before {
  content: '';
  @apply absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent;
  @apply transform -skew-x-12 -translate-x-full;
  @apply transition-transform duration-700;
}

.premium-button:hover::before {
  @apply translate-x-full;
}

/* 响应式设计 */
@media (max-width: 1600px) {
  .px-24 {
    padding-left: 5rem; /* 80px */
    padding-right: 5rem;
  }
  
  .ml-12 {
    margin-left: 2rem;
  }
}

@media (max-width: 1400px) {
  .w-\[30rem\] {
    width: 28rem; /* 448px */
  }
  
  .min-w-\[30rem\] {
    min-width: 28rem;
  }
  
  .px-24 {
    padding-left: 4rem; /* 64px */
    padding-right: 4rem;
  }
  
  .ml-12 {
    margin-left: 1.5rem;
  }
}

@media (max-width: 1200px) {
  .w-\[30rem\] {
    width: 26rem; /* 416px */
  }
  
  .min-w-\[30rem\] {
    min-width: 26rem;
  }
  
  .px-24 {
    padding-left: 3rem; /* 48px */
    padding-right: 3rem;
  }
  
  .ml-12 {
    margin-left: 1rem;
  }
}

@media (max-width: 1024px) {
  .w-\[30rem\] {
    width: 24rem; /* 384px */
  }
  
  .min-w-\[30rem\] {
    min-width: 24rem;
  }
  
  .px-24 {
    padding-left: 2rem; /* 32px */
    padding-right: 2rem;
  }
  
  .ml-12 {
    margin-left: 0.75rem;
  }
}

@media (max-width: 768px) {
  .w-\[30rem\] {
    width: 22rem; /* 352px */
  }
  
  .min-w-\[30rem\] {
    min-width: 22rem;
  }
  
  .max-w-\[34rem\] {
    max-width: 24rem;
  }
  
  .px-24 {
    padding-left: 1rem; /* 16px */
    padding-right: 1rem;
  }
  
  .ml-12 {
    margin-left: 0.5rem;
  }
}

/* 确保内容区域可以正确滚动 */
.tab-content > div {
  height: 100%;
  overflow: auto;
}

/* 优化按钮在小屏幕上的显示 */
@media (max-width: 1024px) {
  .grid-cols-4 {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 640px) {
  .grid-cols-4 {
    grid-template-columns: repeat(1, minmax(0, 1fr));
  }
  
  .premium-button {
    @apply text-xs;
  }
  
  .premium-button .el-icon {
    @apply text-sm;
  }
}
</style>
